package com.base.commons.tools.rest.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.CollectionUtils;

import java.net.URI;
import java.util.Map;

/**
 * @author carl
 */
public class HttpClientRequestFactory extends HttpComponentsClientHttpRequestFactory {
    public static final String SOCKET_TIMEOUT="socketTimeout";
    public static final String CONNECT_TIMEOUT="connectTimeout";
    public static final ThreadLocal<Map<String,Integer>> socketTimeoutThreadLocal = new ThreadLocal<>();
 
    public HttpClientRequestFactory(HttpClient httpClient) {
        super(httpClient);
    }
 
    @Override
    protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
        HttpContext context = HttpClientContext.create();
 
        RequestConfig config = createRequestConfig(getHttpClient());
 
        // 从ThreadLocal中获取超时时间，并设置到context中
        Map<String,Integer> map = socketTimeoutThreadLocal.get();
        if (!CollectionUtils.isEmpty(map)&&
                map.get(SOCKET_TIMEOUT)!=null&&
                map.get(CONNECT_TIMEOUT)!=null) {
            RequestConfig.Builder builder = RequestConfig.copy(config);
            builder.setSocketTimeout(map.get(SOCKET_TIMEOUT));
            builder.setConnectTimeout(map.get(CONNECT_TIMEOUT));
            config = builder.build();
        }
        context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
        return context;
    }
}